<script language="javascript">
	cursession = "<#if curagentuser??>${curagentuser.userid!''}</#if>" ;
	var userid = "${curagentuser.userid!''}" , agentserviceid = "${curagentuser.agentserviceid!''}" , aiid = "<#if serviceAi??>${serviceAi.id!''}</#if>", agentuserid = "${curagentuser.id}";
</script>
<link rel="stylesheet" type="text/css" href="/im/css/ukefu.css">
<link rel="stylesheet" id="skin" type="text/css" href="/im/css/default/ukefu.css">
<script src="/im/js/socket.io.js"></script>
<script type="text/javascript">
		var tipuser = '<#if inviteData??>${inviteData.tipuser}</#if>' , tipusertitle = '<#if inviteData??>${inviteData.tipusertitle!"您有一条新的消息"}</#if>', tipusericon = '<#if inviteData??>/res/image.html?id=${inviteData.tipusericon!"/images/logo2.png"}</#if>' ;
		var newmessage = [] , ring = [];
		newmessage['mp3'] = '/images/message.mp3';
		ring['mp3'] = '/images/ring.mp3';
		var editor , words;
        KindEditor.ready(function (K) {
            editor = K.create('textarea[name="content"]', {
                autoHeightMode: false,
                width: "100%",
                resizeType: 0,
                themeType: 'simple',
                fontsize: 16,
				newlineTag : "br" , 
				filterMode:true,
                items: ['emoticons', 'cut'],
				htmlTags: {img : ['src', 'width', 'height', 'border', 'alt', 'title', 'align', '.width', '.height', '.border'] , br:[]}  ,
				afterChange : function() {
					var count = this.count() ;
					var limitNum = 300;  //设定限制字数
					var pattern = '还可以输入' + limitNum + '字'; 
					var strValue = this.html();
					if(count > limitNum) {
						pattern = ('字数超过限制，请适当删除部分内容');
						//超过字数限制自动截取			 						
						strValue = strValue.substring(0,limitNum);
						editor.html(strValue);      
					} else {
						//计算剩余字数
						var result = limitNum - this.count(); 
						pattern = '还可以输入' +  result + '字'; 
						if(result < 20){
							document.getElementById('surplus').style.color = "red" ;	
						}else{
							document.getElementById('surplus').style.color = "#000000" ;								
						}
					}
					
					words = this.count("text") ;
					document.getElementById('surplus').innerHTML = count+"/"+limitNum+" , " + pattern; //输入显示
					 ////////
				},
				afterCreate : function() { //设置编辑器创建后执行的回调函数
		            var self = this;
		            //Ctrl+Enter提交表单
		            K.ctrl(document, 13, function() {
		                self.sync();
		                sendMessage();
		            });
		            K.ctrl(self.edit.doc, 13, function() {
		                self.sync();
		                sendMessage();
		            });
		        }
            });
        });
		KindEditor.options.cssData = "body { font-size: 15px; font-family:'Microsoft Yahei', 'Helvetica', 'Simsun', 'Arial';}";
		var R3Ajax = {
				ajax:function(opt){
					var xhr = this.createXhrObject();
					xhr.onreadystatechange = function(){
						if(xhr.readyState!=4) return ;
						(xhr.status===200 ?
							opt.success(xhr.responseText,xhr.responseXML):
							opt.error(xhr.responseText,xhr.status));
					}
					xhr.open(opt.type,opt.url,true);
					if(opt.type!=='post') 
						opt.data=null;
					else
						xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
					opt.data = this.parseQuery(opt.data);
					xhr.send(opt.data);
				},
				post:function(url,success,data){
					var popt = {
						url:url,
						type:'post',
						data:data,
						success:success,
						error:function(data){}
					}
					this.ajax(popt);
				},
				get:function(url,success){
					var gopt = {
						url:url,
						type:'get',
						success:success,
						error:function(){}
					}
					this.ajax(gopt);
				},
				createXhrObject:function(){
					var methods = [
						function(){ return new XMLHttpRequest();},
						function(){ return new ActiveXObject('Msxml2.XMLHTTP');},
						function(){ return new ActiveXObject('Microsoft.XMLHTTP');}
					];
					for(var i=0;len=methods.length,i<len;i++){
						try{
							methods[i]();
						}catch(e){
							continue;
						}
						this.createXhrObject = methods[i];
						return methods[i]();
					}
					throw new Error('Could not create an XHR object.');
				},
				parseQuery:function(json){
					if(typeof json == 'object'){
						var str = '';
						for(var i in json){
							str += "&"+i+"="+encodeURIComponent(json[i]);
						}
						return str.length==0 ? str : str.substring(1);
					}else{
						return json;
					}
				},
				audioplayer:function(id, file, loop) {
				    var audioplayer = document.getElementById(id);
				    if (audioplayer != null) {
				        document.body.removeChild(audioplayer);
				    }

				    if (typeof(file) != 'undefined') {
				        if (navigator.userAgent.indexOf("MSIE") > 0) { // IE 
				            var player = document.createElement('bgsound');
				            player.id = id;
				            player.src = file['mp3'];
				            player.setAttribute('autostart', 'true');
				            if (loop) {
				                player.setAttribute('loop', 'infinite');
				            }
				            document.body.appendChild(player);

				        } else { // Other FF Chome Safari Opera 
				            var player = document.createElement('audio');
				            player.id = id;
				            player.setAttribute('autoplay', 'autoplay');
				            if (loop) {
				                player.setAttribute('loop', 'loop');
				            }
				            document.body.appendChild(player);

				            var mp3 = document.createElement('source');
				            mp3.src = file['mp3'];
				            mp3.type = 'audio/mpeg';
				            player.appendChild(mp3);
				        }
				    }
				}
			};
		var R3Helper = {
			resize : function(){
				var height = document.body.offsetHeight ;
				document.getElementById('above').style.height = (height - 194 - 50)+"px" ;
			}
		}
		window.onbeforeunload = function(){
			return "您确定断开对话？" ;
		}
    </script>
<div class="main-agentuser">
	<div class="chat-agent">
		<h1 class="site-h1">
			测试智能机器人（${serviceAi.name!''}）对话 <span style="float: right; margin-right: 5px;">
				<select name="" class="layui-input ukefu-input" lay-ignore
				onchange="location.href='/apps/xiaoe/chat.html?aiid='+$(this).val();">
					<#if serviceAiList??> 
					<#list serviceAiList as ai>
					<option value="${ai.id!''}"<#if aiid?? && aiid== ai.id>selected="selected"</#if>>${ai.name!''}
					</option>
					</#list> 
					</#if>
			</select>
			</span>
		</h1>
		<div id="chat_msg_list" class="chat-message chat_msg_list" style="height:auto;">
			<div class="chat-above" id="above" style="margin-top:0px;">
            	<div class="clearfix message  welcome"> <span id="welcome-message"><#if inviteData.aimsg?? && inviteData.aimsg!=''>${inviteData.aimsg?no_esc}<#else>${(inviteData.dialog_message!'欢迎您来咨询！')?no_esc}</#if></span></div>
				<#if chatMessageList?? && chatMessageList.content??>
					<#list chatMessageList.content?reverse as chatMessage>
						<#if chatMessage.userid?? && userid?? && userid == chatMessage.userid>
							<div class="clearfix chat-block">
								<div class="chat-right"> 
									<img class="user-img" src="/im/img/user.png" alt="">
									<div class="chat-message">
										<label class="time">${chatMessage.createtime!''}</label>
										<label class="user">${chatMessage.username!''}</label> 
									</div>
									<div class="chatting-right">
										<i class="arrow arrow${inviteData.consult_dialog_color!''}"></i>
										<div class="chat-content theme${inviteData.consult_dialog_color!''}"><#include "/apps/im/media/message.html"></div>
									</div>
								</div>
							</div>
						<#else>
							<div class="clearfix chat-block">
								<div class="chat-left"> 
									<img class="user-img" src="<#if inviteData?? && inviteData.consult_dialog_headimg??>/res/image.html?id=${inviteData.consult_dialog_headimg?url}<#else>/images/agent.png</#if>" alt="">
									<div class="chat-message">
										<label class="user">${inviteData.ainame!'小E'}</label> 
										<label class="time">${chatMessage.createtime!''}</label>										
									</div>
									<div class="chatting-left">
										<i class="arrow"></i>
										<div class="chat-content"><#include "/apps/im/media/message.html"></div>
									</div>
								</div>
							</div>
						</#if>
					</#list>
				</#if>
			</div>
            <div class="chat-bottom" id="bottom">
				<textarea id="message" name="content" style="visibility:hidden;"></textarea>
				<div class="btn-push clearfix">
					<div style="float:left;height:34px;line-height:34px;margin: 10px 20px 10px 5px;" id="surplus">0/200</div>
					<button type="button" class="send-btn active special  clearfix" id="sent" onclick="sendMessage()">
						发送
					</button>
				</div>
			</div>
		</div>
	</div>
</div>
<div class="ukefu-chat-prop">
	<div class="ukefu-prop-list">
		<div class="layui-side-scroll">
			<div class="layui-tab layui-tab-card" style="margin-top:0px;">
			  <ul class="layui-tab-title">
			    <li class="layui-this">测试对话</li>
			    <!-- 下个版本增加的功能 ， 查看对话的DEBUG信息
			    <li>调试信息</li>
			     -->
			  </ul>
			  <div class="layui-tab-content" style="padding: 5px 0px 0px;">
			    <div class="layui-tab-item layui-show">
			    	<div class="box">
						<div class="box-title">
							<h1 class="site-h1" style="background-color:#EEEEEE;">
								<img src="/im/img/ask.png" style="width:22px;"/>
								热门问题
							</h1>
						</div>
						<div class="box-body" id="ukefu-comments" style="padding:0px 10px;position: relative;">
							<ul id="ukefu-workorders-comment">
								<#include "/apps/business/xiaoe/chat/topic.html">	
			                </ul>
						</div>
					</div>
			    </div>
			    <!-- 下个版本增加的功能 ， 查看对话的DEBUG信息
			    <div class="layui-tab-item layui-show">
			    	<div class="box">
						<div class="box-title">
							<h1 class="site-h1" style="background-color:#EEEEEE;">
								<img src="/im/img/ask.png" style="width:22px;"/>
								调试信息
							</h1>
						</div>
						<div class="box-body" style="padding:0px 10px;position: relative;">
							
						</div>
					</div>
			    </div>
			     -->
			  </div>
			</div>
			
		</div>
	</div>
</div>
<script>
	layui.use(['element', 'flow'], function(){
	  	var element = layui.element ;
	  	var flow = layui.flow;
		flow.load({
		    elem: '#ukefu-comments' //指定列表容器
		   	,scrollElem:".layui-side-scroll"
		    ,done: function(page, next){ //到达临界点（默认滚动触发），触发下一页
		      $.get('/apps/xiaoe/chat/toptopic.html?aiid=<#if serviceAi>${serviceAi.id!''}&</#if>p='+page, function(res){
		        //假设你的列表返回在data集合中
		        //执行下一页渲染，第二参数为：满足“加载更多”的条件，即后面仍有分页
		        //pages为Ajax返回的总页数，只有当前页小于总页数的情况下，才会继续出现加载更多
		        next($('#ukefu-workorders-comment').append(res) , $(res).length > 0);    
		      });
		    }
		});
	});
	var service_end = false ;
	R3Helper.resize();
    // 调查问卷
    var diaShade=document.getElementById('diaShade');
    var dialogWrap=document.getElementById('dialogWrap');
    function popup(para) {
        diaShade.style.display=para;
        dialogWrap.style.display=para;
    }
    document.getElementById('above').scrollTop = document.getElementById('above').scrollHeight  ;	//滚动到 对话内容的 底部
    // 参数连接
	var hostname = location.hostname ;
    var socket = io.connect('${schema!'http'}://'+hostname+':${import}/im/ai');
    socket.on('connect',function(){
        //service.sendRequestMessage(); 
		//output('<span id="connect-message">'+ new Date().format("yyyy-MM-dd hh:mm:ss") + ' 开始沟通' +'</span>' , 'message connect-message');
    	socket.emit('new', {
    		<#if contacts?? && contacts.name??>
			name : "${contacts.name!''}",
			phone:"${contacts.phone!''}",
			email:"${contacts.email}",
			memo:"${contacts.memo!''}",
			</#if>
			orgi:"${orgi!''}",
			appid : "${appid!''}",
			aiid : "${aiid!''}",
			userid:"${userid!''}",
			user:"${userid!''}",
			session:"${sessionid!''}",
			debug:true,
			osname:"${(osname!'')?url}",
			browser:"${(browser!'')?url}"
			<#if skill??>,skill:"${skill}"</#if>
			<#if username??>,nickname:"${username}"</#if>
			<#if agent??>,agent:"${agent}"</#if>
			<#if title??>,title:"${title?url}"</#if>
			<#if traceid??>,url:"${url?url}"</#if>
			<#if traceid??>,traceid:"${traceid}"</#if>
		});
    })
    socket.on("agentstatus",function(data){
    	var message = "${inviteData.aisuccesstip!''}" ;
    	if(message != ""){
    		document.getElementById('connect-message').innerHTML = message;
    	}else{
       		document.getElementById('connect-message').innerHTML = data.message;
    	}
    })
    socket.on("status",function(data){
    	var message = "${inviteData.aisuccesstip!''}" ;
    	if(message == ""){
       		message = data.message ;
    	}
		output('<span id="connect-message">'+message+'</span>' , 'message connect-message');     
		if(data.messageType == "end"){
			service_end = true ;
			editor.readonly();
		}
    })
    socket.on('message', function(data) {
    	console.log(data);
    	debugger;
    	var chat=document.getElementsByClassName('chatting-left').innerText;
        chat = data.message;
        if(data.messageType == "image"){
        	chat = "<img src='"+data.message+"' class='ukefu-media-image'>" ;
        }else if(data.messageType == "voice"){
        	chat = template($('#message_tpl').html(), {data: data}) ;
        }else if(data.messageType == "trans"){
        	chat = template($('#message_tpl').html(), {data: data}) ;
        }else if(data.messageType == "hungup"){
        	chat = template($('#message_tpl').html(), {data: data}) ;
        }
        var text = '<ul class="info-list">' ;
        if(data.suggest!=null){
        	for(inx =0 ; inx < data.suggest.length ; inx++){
        		var item = data.suggest[inx] ;
        		text = text + '<li class="ukefu-suggest-item"><a href="javascript:void(0)" class="suggestitem" onclick="sendMessageTextWithID(\''+item.title.replace(/'/g,"")+'\' , \''+item.id+'\')">'+item.title+'</a></li>' ;
        	}
        	text = text + "</ul>";
        	chat = chat + text ;
        }
		if(data.calltype == "in"){
			var topicedit = '<div class="ukefu-ai-tip" style="border-color:#aaa;"><span class="ukefu-ai-btn ukefu-ai-quickagent"  style="border-color:#aaa;" data-toggle="ajax" data-title="编辑" href="/apps/xiaoe/chat/match.html?type=debug&aiid=<#if serviceAi??>${serviceAi.id!''}</#if>&id='+data.id+'&type='+data.typeid+'" data-width="950" data-height="500">查看匹配的关键词条件</span></div>' ;
			output('<div class="chat-right"> <img class="user-img" src="/im/img/user.png" alt=""><div class="chat-message"><label class="time">'+data.createtime+'</label><label  class="user">'+data.nickName+'</label> </div><div class="chatting-right"><i class="arrow arrow${inviteData.consult_dialog_color!''}"></i><div class="chat-content theme${inviteData.consult_dialog_color!''}">'+chat+topicedit+'</div></div>' , "chat-block");
		}else if(data.calltype == "out"){
			/***延迟1秒执行，不然太快****/
			
			setTimeout(function(){
				var ext_message = "" ;
				//开启知识点评价功能
				<#if aiConfig?? && aiConfig.topicuseful>
				if(data.topic == true){
					ext_message = "<div class='ukefu-ai-tip' id='ukefu_ai_msg_"+data.id+"'><span><#if aiConfig.topicusefulmsg?? && aiConfig.topicusefulmsg!=''>${aiConfig.topicusefulmsg!''}<#else>此条知识是否解决了问题？</#if></span><span><span class='ukefu-ai-btn ukefu-ai-btn-ok' data-id='"+data.id+"'><i class='iconfont'>&#xe640;</i>&nbsp;&nbsp;<#if aiConfig.topicusefulok?? && aiConfig.topicusefulok!=''>${aiConfig.topicusefulok}<#else>已解决</#if></span><span class='ukefu-ai-btn ukefu-ai-btn-no'  data-id='"+data.id+"'><i class='iconfont'>&#xe629;</i>&nbsp;&nbsp;<#if aiConfig.topicusefulno?? && aiConfig.topicusefulno!=''>${aiConfig.topicusefulno}<#else>未解决</#if></span></span></div>" ;
				}
				</#if>
				var topicedit = "";
				if(data.topic == true){
					topicedit = '<div class="ukefu-ai-tip"><span class="ukefu-ai-btn ukefu-ai-quickagent" data-toggle="ajax" data-title="编辑" href="/apps/xiaoe/chat/match.html?type=debug&aiid=<#if serviceAi??>${serviceAi.id!''}</#if>&id='+data.id+'&type='+data.typeid+'" data-width="950" data-height="500">查看匹配的关键词条件</span><span class="ukefu-ai-btn ukefu-ai-quickagent" data-toggle="ajax" data-title="编辑" href="/apps/xiaoe/knowledge/edit.html?debug=true&aiid=<#if serviceAi??>${serviceAi.id!''}</#if>&id='+data.topicid+'&type='+data.typeid+'" data-width="950" data-height="500">编辑命中的知识条目</span></div>' ;
				}else if(data.mround == true){
					topicedit = '<div class="ukefu-ai-tip"><span class="ukefu-ai-btn ukefu-ai-quickagent" data-toggle="ajax" data-title="编辑" href="/apps/xiaoe/chat/match.html?type=debug&aiid=<#if serviceAi??>${serviceAi.id!''}</#if>&id='+data.id+'&type='+data.typeid+'" data-width="950" data-height="500">查看匹配的关键词条件</span><span class="ukefu-ai-btn ukefu-ai-quickagent" data-toggle="ajax" data-title="编辑" href="/apps/xiaoe/mrounds/edit.html?debug=true&id='+data.quesid+'&dataid='+data.dataid+'&type='+data.mtype+'" data-width="950" data-height="500">编辑命中的知识条目</span></div>' ;
				} 
				output('<div class="chat-left"> <img class="user-img" src="<#if inviteData?? && inviteData.aiicon??>/res/image.html?id=${inviteData.aiicon?url}<#elseif inviteData?? && inviteData.consult_dialog_headimg??>/res/image.html?id=${inviteData.consult_dialog_headimg?url}<#else>/images/agent.png</#if>" alt=""><div class="chat-message"><label  class="user">${inviteData.ainame!'小E'}</label><label class="time">'+data.createtime+'</label> </div><div class="chatting-left"><i class="arrow"></i><div class="chat-content">'+chat + ext_message+topicedit+'</div></div>' , "chat-block");
				
				if(tipuser && tipuser == 'true'){
					R3Helper.showNotice(tipusertitle , data.message , tipusericon);
				}
				R3Ajax.audioplayer('audioplane', newmessage, false); // 播放
			} , 500);
		}
    });
    
    socket.on('disconnect',function() {
        output('<span id="connect-message">连接服务失败，智能在线咨询服务不可用</span>' , 'message connect-message');
    });
    function sendDisconnect(){
        socket.disconnect();
    }
    function sendMessage() {
		editor.sync();
		var count = editor.count("text");
		if(count>0 && service_end == false){
	        var message = document.getElementById('message').value;
	        sendMessageText(message);
		}else if(service_end == true){
			alert("服务器已断开和您的对话");	
		}
		editor.html('');
    }
    function sendMessageText(message){
    	sendMessageTextWithID(message);
    }
    function sendMessageTextWithID(message , id){
    	if(message!= ""){ 
			socket.emit('message', {
					appid : "${appid!''}",
					userid:"${userid!''}",
					username:"${username!''}",
					channel:"webim",
					debug:true,
					type:"message" ,
					contextid:"${sessionid!''}",
					orgi:"${orgi!''}",
					mediaid:id,
					message :  message
			});
		}
    }
    function output(message , clazz) {
		if(clazz == "message connect-message"){
			var messages = document.getElementsByClassName("connect-message") ;
			for(inx =0 ; inx < messages.length ; ){
				document.getElementById('above').removeChild(messages[inx]) ;
				inx++ ;
			}			
		}
        var element = ("<div class='clearfix "+clazz+"'>" +" " + message + "</div>");
        document.getElementById('above').innerHTML= (document.getElementById('above').innerHTML + element);
		document.getElementById('above').scrollTop = document.getElementById('above').scrollHeight  ;
    }
	function update(id , message) {
        document.getElementById(id).innerHTML= message;
    }
    
    var message={
        // text:data.message,
        // picture:function(){

        // }
        // file:function(){

        // }
        // lang:function(){

        // }
        // goods:function(){

        // }
        // POI:function(){

        // }

    }
    // 回车事件
    document.onkeyup=function(e){
        if(!e) e=window.event;
        if((e.keyCode||e.which)==13){
            document.getElementById('sent').click();
        }
    }
	window.onresize = function(){
		R3Helper.resize();		
	};
	$(document).ready(function(){
		$(document).on('click','.ukefu-ai-btn-ok', function ( e ) {
			$('#ukefu_ai_msg_'+$(this).data("id")).empty().html("<span class='ukefu-ai-btn-ok-tip'><i class='iconfont'>&#xe61b;</i>&nbsp;&nbsp;${aiConfig.topicusefultip!''}</span>") ;
			$.ajax({
	             type: "GET",
	             url: "/rest/webim/message/useful.json?id="+$(this).data("id"),
	             dataType: "json",
	             success: function(data){
	             	
	             }
	         });
		});
		$(document).on('click','.ukefu-ai-btn-no', function ( e ) {
			let obj = $(this) ;
			$.ajax({
	             type: "GET",
	             url: "/rest/webim/message/unuseful.json?id="+$(this).data("id"),
	             dataType: "json",
	             success: function(data){
	             	
	             }
	         });
			$('#ukefu_ai_msg_'+$(obj).data("id")).empty().html("<span class='ukefu-ai-btn-no-tip'><i class='iconfont'>&#xe62d;</i>&nbsp;&nbsp;${aiConfig.topicusefultip!''}</span><span>机器人测试状态下，无法转人工</span>") ;

			
		});
	});
</script>